package com.x2.modular.system.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.x2.base.pojo.node.LayuiTreeNode;
import com.x2.base.pojo.node.ZTreeNode;
import com.x2.base.pojo.page.LayuiPageFactory;
import com.x2.core.constant.SysTreeNode;
import com.x2.core.constant.factory.ConstantFactory;
import com.x2.core.exception.enums.BizExceptionEnum;
import com.x2.core.util.ToolUtil;
import com.x2.kernel.model.exception.ServiceException;
import com.x2.modular.system.entity.Dept;
import com.x2.modular.system.mapper.DeptMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 部门表 服务实现类
 *
 * @author changpeng
 * @date 2021-01-11
 */
@Service
public class DeptService extends ServiceImpl<DeptMapper, Dept> {

    @Resource
    private DeptMapper deptMapper;

    /**
     * 新增部门
     *
     * @param dept: 参数
     */
    @Transactional(rollbackFor = Exception.class)
    public void addDept(Dept dept) {
        if (ToolUtil.isOneEmpty(dept, dept.getSimpleName(), dept.getFullName(), dept.getPid())) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        this.deptSetPids(dept);
        this.save(dept);
    }

    /**
     * 修改部门
     *
     * @param dept：参数
     */
    @Transactional(rollbackFor = Exception.class)
    public void editDept(Dept dept) {
        if (ToolUtil.isOneEmpty(dept, dept.getDeptId(), dept.getSimpleName(), dept.getFullName(), dept.getPid())) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        this.deptSetPids(dept);
        // 获取要移动的子部门
        List<Dept> moveDeptList = getMovePidsDept(dept.getDeptId(), dept.getPids());
        this.updateById(dept);
        ConstantFactory.me().removeDeptById(dept.getDeptId());
        if (moveDeptList != null) {
            // 子部门移动
            for (Dept child : moveDeptList) {
                this.updateById(child);
                ConstantFactory.me().removeDeptById(child.getDeptId());
            }
        }
    }

    /**
     * 删除部门
     *
     * @param deptId：部门id
     */
    @Transactional(rollbackFor = Exception.class) 
    public void deleteDept(Long deptId) {
        Dept dept = deptMapper.selectById(deptId);
        List<Dept> subDepts = deptMapper.likePids(dept.getDeptId());
        for (Dept temp : subDepts) {
            this.removeById(temp.getDeptId());
            ConstantFactory.me().removeDeptById(temp.getDeptId());
        }
        this.removeById(dept.getDeptId());
        ConstantFactory.me().removeDeptById(dept.getDeptId());
    }

    /**
     * 修改时获取需要改变部门路径的部门信息
     *
     * @param deptId:  修改的部门id
     * @param newPids: 修改后的部门路径
     * @return 需要改动的部门（修改成了新的部门路径）
     */
    public List<Dept> getMovePidsDept(Long deptId, String newPids) {
        Dept dbDept = this.getById(deptId);
        if (dbDept == null) {
            return null;
        }
        String oldPids = dbDept.getPids() + "[" + deptId + "],";
        newPids += "[" + deptId + "],";
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
        queryWrapper.apply("pids like {0}", oldPids);
        List<Dept> deptList = this.list(queryWrapper);
        for (Dept dept : deptList) {
            dept.setPids(ToolUtil.replaceStr(dept.getPids(), oldPids, newPids));
        }
        return deptList;
    }

    public List<Dept> likePids(Long deptId) {
        return deptMapper.likePids(deptId);
    }

    /**
     * 获取ztree的节点列表
     *
     * @return 结果
     */
    public List<ZTreeNode> tree() {
        return this.baseMapper.tree();
    }


    /**
     * 获取所有部门列表
     *
     * @param condition:  条件
     * @param deptId：部门id
     * @return 结果
     */
    public Page<Map<String, Object>> list(String condition, Long deptId) {
        Page page = LayuiPageFactory.defaultPage();
        return this.baseMapper.list(page, condition, deptId);
    }

    /**
     * 获取部门列表
     *
     * @param condition：部门名称
     * @param deptId：部门id
     * @return 结果
     */
    public List<Map<String, Object>> deptList(String condition, Long deptId) {
        return this.baseMapper.list(condition, deptId);
    }

    /**
     * @return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @Author duangy
     * @Description 获取第一级部门
     * @Date 2021/6/15 13:50
     * @Param [condition, deptId]
     **/
    public List<Map<String, Object>> deptRootList(String condition, Long deptId) {
        return this.baseMapper.deptRootList(condition, deptId);
    }

    /**
     * 设置部门的父级ids
     *
     * @param dept: 对象
     */
    private void deptSetPids(Dept dept) {
        if (ToolUtil.isEmpty(dept.getPid()) || dept.getPid().equals(0L)) {
            dept.setPid(0L);
            dept.setPids("[0],");
        } else {
            Long pid = dept.getPid();
            Dept temp = this.getById(pid);
            String pids = temp.getPids();
            dept.setPid(pid);
            dept.setPids(pids + "[" + pid + "],");
        }
    }

    public List<SysTreeNode> getSelectTreeData() {
        List<SysTreeNode> deptTree = new ArrayList<>();
        QueryWrapper<Dept> deptQueryWrapper = new QueryWrapper<>();
        deptQueryWrapper.orderByAsc("sort");
        List<Dept> deptList = this.list(deptQueryWrapper);
        List<SysTreeNode> tempDeptTree = new ArrayList<>();
        for (Dept dept : deptList) {
            tempDeptTree.add(SysTreeNode.changeDeptNode(dept, null));
        }
        if (tempDeptTree.size() > 0) {
            deptTree = SysTreeNode.createTree(tempDeptTree);
        }
        return deptTree;
    }


    /**
     * 根据名称获取部门，只取第一个
     *
     * @param name：名称
     * @return 部门
     */
    public Dept getByName(String name) {
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("simple_name", name);
        List<Dept> deptList = this.list(queryWrapper);
        return deptList != null && deptList.size() > 0 ? deptList.get(0) : null;
    }

    /**
     * 根据id获取部门路径
     *
     * @param deptId
     * @return
     */
    public String getPath(Long deptId) {
        if (deptId == null) {
            return "";
        }
        Dept dept = this.getById(deptId);
        if (dept == null) {
            return "";
        }
        String pids = dept.getPids();
        String path = "";
        String[] array = ToolUtil.splitStr(pids, ',');
        for (String s : array) {
            if (s.trim().length() == 0) {
                continue;
            }
            s = ToolUtil.replaceStr(s, "[", "");
            s = ToolUtil.replaceStr(s, "]", "");
            Dept temp = this.getById(ToolUtil.toLong(s));
            if (temp != null) {
                path += temp.getSimpleName() + " - ";
            }
        }
        return path + dept.getSimpleName();
    }
}
